package models

import (
	"gorm.io/gorm"
)

type Goodsroom struct {
	gorm.Model
	Number string  `json:"number" gorm:"type:varchar(32);not null;comment:入库单号"`
	Cate   string  `json:"cate" gorm:"type:varchar(20);not null;comment:单据类型"`
	Room   string  `json:"room" gorm:"type:varchar(30);not null;comment:仓库"`
	Num    int     `json:"num" gorm:"type:int(10);not null;comment:入库数量"`
	Price  float64 `json:"price" gorm:"type:decimal(10,2);not null;comment:入库金额"`
	Name   string  `json:"name" gorm:"type:varchar(20);not null;comment:制单人"`
}

func (g *Goodsroom) Creates() error {
	return DB.Create(&g).Error
}

func (g *Goodsroom) List(room string, page, pageSize int) (goodsroom []*Goodsroom, err error) {
	err = DB.Where("room like ?", room).Scopes(Paginate(page, pageSize)).Find(&goodsroom).Error
	return
}

func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {

		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
